package com.yoomiito.app.pay

import cn.droidlover.xdroidmvp.net.ApiException
import cn.droidlover.xdroidmvp.net.ApiSubscriber
import cn.droidlover.xdroidmvp.net.BaseModel
import cn.droidlover.xdroidmvp.net.XApi
import com.yoomiito.app.R
import com.yoomiito.app.base.BaseActivity
import com.yoomiito.app.model.order.PayResultInfo
import com.yoomiito.app.net.YmApi
import com.yoomiito.app.ui.my.psw.SetPayPswActivity
import com.yoomiito.app.utils.*
import com.yoomiito.app.utils.encrypt.AESUtils
import com.yoomiito.app.widget.PasswordView_1
import com.yoomiito.app.widget.TipDialog
import com.yoomiito.app.widget.dialog.PayDialog
import com.yoomiito.app.widget.dialog.PswInputDialog

@Deprecated("仅用于商学院课程支付。如商学院课程支付有改变，则使用PayUtilsManager")
class NewPayUtils(var context: BaseActivity<*>?) {
    lateinit var payInfo: PayInfo
    private var mPayDialog: PayDialog? = null
    private var mTipDialog: TipDialog? = null
    private var mPswInputDialog: PswInputDialog? = null
    var payResultListener: (PayResult) -> Unit = {}

    /**
     * 支付方式弹窗
     */
    fun showDialog() {
        if (mPayDialog == null) {
            mPayDialog = PayDialog(context!!)
            mPayDialog?.setOnResultListener { moneyPay, wxPay, aliPay,offline,qiick, dismiss ->
                mPayDialog?.dismiss()
                if (dismiss) return@setOnResultListener
                if (moneyPay == 0 && wxPay == 0 && aliPay == 0) {
                    YMToast.showText("请选择支付方式")
                    return@setOnResultListener
                }
                if (moneyPay == 1 && wxPay == 0 && aliPay == 0) {
                    //余额支付 需要密码框
                    if (UserInfoConfig.havePayPsw()) {
                        showPsw()
                    } else {
                        showSetPayPswTip()
                    }
                } else {
                    //非余额支付
                    context?.showLoading()
                    pay(payInfo.orderId,
                            wxPay,
                            aliPay,
                            if (moneyPay == 1) payInfo.account else "0",
                            payInfo.orderType,
                            "",
                            payInfo.yo_money_not
                    )

                }
            }
        }
        mPayDialog?.setBalance(payInfo.balance)
        mPayDialog?.setPayMoney(payInfo.payMoney)
        mPayDialog?.setRadio(payInfo.radio)
        mPayDialog?.show()
    }

    /**
     * 提示设置密码框
     */
    private fun showSetPayPswTip() {
        if (mTipDialog == null) {
            mTipDialog = TipDialog(context, TipDialog.TYPE_SELECT)
            mTipDialog?.setTopTipText(ResUtil.getString(R.string.my_tip))
            mTipDialog?.setTipText("为确保余额资金安全，请先设置千年艾支付密码")
            mTipDialog?.setSureText("马上设置")
            mTipDialog?.setcancleText("取消")
            mTipDialog?.setDialogCallback(object : TipDialog.Dialogcallback {
                override fun btnConfirm() {
                    SetPayPswActivity.start(context)
                }

                override fun cancel(): Boolean = false

            })
        }
        mTipDialog?.show()
    }

    private fun showPsw() {
        if (mPswInputDialog == null) {
            mPswInputDialog = PswInputDialog(context!!)
            mPswInputDialog?.setTextChangedListener(object : PasswordView_1.TextChangedListener(){
                override fun textChanged(changeText: CharSequence) {

                }

                override fun textCompleted(text: CharSequence) {//余额支付
                    context?.showLoading()
                    pay(payInfo.orderId, 0, 0, payInfo.account, payInfo.orderType, AESUtils.rsaEncrypt(text.toString()), payInfo.yo_money_not)
                }

                override fun forgetPsw() {
                    mPswInputDialog?.dismiss()
                }
            })
        }
        mPswInputDialog?.show()
    }

    private fun pay(id: String, wx: Int, ali: Int, account: String, orderType: Int, psw: String, yo_money_not: Int) {
        L.i("支付金额: " +
                "\nid:" + id +
                " \nwx:" + wx +
                " \nali:" + ali +
                " \naccount:" + account +
                " \norderType:" + orderType +
                " \npsw:" + psw +
                " \nyo_money_not:" + yo_money_not)
        YmApi.getYmService()
                .multipPay(id, wx, ali, account, orderType, psw, yo_money_not.toString())
                .compose<BaseModel<PayResultInfo>>(context?.bindToLifecycle())
                .compose(XApi.getApiTransformerData())
                .compose(XApi.getScheduler())
                .subscribe(object : ApiSubscriber<PayResultInfo>() {
                    override fun onSuccess(payResultInfo: PayResultInfo) {
                        context?.dismissLoading()
                        if ("accountpay" == payResultInfo.pay_type) {
                            mPswInputDialog?.dismiss()
                            dispatchPayResult(PayResult.PaySuccess)
                        } else {
                            dispatchPayResult(PayResult.CallOtherPayUtils, payResultInfo.pay_type, payResultInfo.out_trade_no)
                            if ("wxpay" == payResultInfo.pay_type) {
                                PayTypeUtils.wxPay(payResultInfo.data)
                            } else {
                                PayTypeUtils.aliPay(context!!, payResultInfo.data.alipay_order)
                            }

                        }
                    }

                    override fun onFail(error: ApiException) {
                        context?.dismissLoading()
                        if (error.code == ApiException.PAY_PSW_ERROR) {
                            mPswInputDialog?.showErrorTip(true, ResUtil.getString(R.string.psw_error))
                        } else if (error.code == ApiException.BALANCE_INSUFFICIENT) {
                            YMToast.showText(ResUtil.getString(R.string.balance_poor))
                            if (mPswInputDialog != null) {
                                mPswInputDialog?.dismiss()
                            }
                        } else if (error.code == ApiException.YOUMI_INSUFFICIENT) {//优米数量不足
                            YMToast.showText(error.msg)
                            if (mPswInputDialog != null) {
                                mPswInputDialog?.dismiss()
                            }
                            context?.showLoading()
                            //有米不足 下发通知
                            dispatchPayResult(PayResult.YouMiShortage)
                        } else {
                            if (mPswInputDialog != null) {
                                mPswInputDialog?.showErrorTip(false, "")
                            } else {
                                YMToast.showText(error.msg)
                                if (mPswInputDialog != null) {
                                    mPswInputDialog?.dismiss()
                                }
                            }
                            //下发支付结果 支付失败
                            dispatchPayResult(PayResult.PayFail)
                        }
                    }
                })
    }

    /**
     * 下发支付状态
     */
    private fun dispatchPayResult(payState: Int,//支付状态
                                  payType: String = "",//支付类型
                                  queryOrderId: String = ""//查询订单id
    ) {
        payResultListener(PayResult(payState, payType, queryOrderId))
    }

    /**
     * 释放所有
     */
    fun release() {
        context = null
        mPayDialog = null
        mTipDialog = null
        mPswInputDialog = null
    }
}